package web.user;

import bean.Type;
import bean.Union;
import bean.User;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.TypeEntity;
import entity.UserEntity;
import entity.VideoEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UserList",urlPatterns = "/dao/userList")
public class UserList extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String jsonString = FANREN.getJson(request);
        Union union = JSON.parseObject(jsonString,Union.class);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query;
        if(union.getSearch().equals("")){
            query = em.createQuery("select u from UserEntity u");
        } else {
            query = em.createQuery("select u from UserEntity u where u.name like '%" + union.getSearch() + "%'");
        }

        List<UserEntity> list = query.getResultList();
        int totalPage = list.size();
        int pos = (union.getCurrentPage() - 1) * 8;

        List<User> userList = new ArrayList<>();
        for (int i=0,j=pos; i<8&&j<list.size(); i++,j++) {
            User user = new User(""+list.get(j).getUid(),list.get(j).getName(),list.get(j).getEmail(),list.get(j).getPhone(),list.get(j).getVip());
            userList.add(user);
        }
        String returnString = "{\"tableData\":" + JSON.toJSONString(userList) +",\"totalPage\":" + totalPage + "}";
        response.getWriter().write(URLEncoder.encode(returnString,StandardCharsets.UTF_8));
    }
}
